﻿using FairyGUI;
using System.Collections;
using UnityEngine;
/// <summary>
/// 调试界面
/// </summary>
public class DebugInfo {

    static GTextField _debugText;
    static Queue _messages;

    public static void InitDebugView()
    {
        if (Constants.DEBUG_GAME)
        {
            _messages = new Queue();

            UIPackage.AddPackage("UI/调试界面");
            GComponent debugComp = UIPackage.CreateObject("调试界面", "调试界面").asCom;
            GRoot.inst.AddChild(debugComp);

            _debugText = debugComp.GetChild("调试消息").asTextField;
        }
    }

    public static void DestroyView()
    {
        if (Constants.DEBUG_GAME)
        {
            UIPackage.RemovePackage("UI/调试界面");
        }
    }

    /// <summary>
    /// 输出日志
    /// </summary>
    /// <param name="message"></param>
    public static void Log(string message)
    {
        Debug.Log(message);
        if (Constants.DEBUG_GAME)
        {
            if (_messages == null)
            {
                _messages = new Queue();
            }
            PackMessage(message, 0);
        }
    }

    public static void Warning(string message)
    {
        Debug.LogWarning(message);
        if (Constants.DEBUG_GAME)
        {
            if (_messages == null)
            {
                _messages = new Queue();
            }
            PackMessage(message, 1);
        }
    }

    public static void Error(string message)
    {
        Debug.LogError(message);
        if (Constants.DEBUG_GAME)
        {
            if (_messages == null)
            {
                _messages = new Queue();
            }
            PackMessage(message, 2);
        }
    }

    static void PackMessage(string message, int level)
    {
        string packedMsg = "";
        switch (level)
        {
            case 0:
                packedMsg += ">> " + message;
                break;

            case 1:
                packedMsg += "[color=#ffff00]>> " + message + "[/color]";
                break;

            case 2:
                packedMsg += "[color=#ff0000]>> " + message + "[/color]";
                break;
        }
        packedMsg += "\n";
        _messages.Enqueue(packedMsg);
        if (_messages.Count > Constants.DEBUG_MSG_LENGTH)
        {
            _messages.Dequeue();
        }
    }

    static string BuildMessage()
    {
        string messageStr = "";
        foreach (string s in _messages)
        {
            messageStr += s;
        }
        return messageStr;
    }

    public static void UpdateDebugInfo()
    {
        if (Constants.DEBUG_GAME)
        {
            if (_debugText != null)
            {
                _debugText.text = BuildMessage();
                if (_debugText.actualHeight >= GRoot.inst.actualHeight)
                {
                    _debugText.y = GRoot.inst.actualHeight - _debugText.actualHeight;
                }
            }
        }
    }
}
